/**
 * 公司部门联动选择组件
 */
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { TreeSelect, Spin } from 'antd';
import request from '@/utils/request';
import Locale from '@/utils/locale';
import { getUserOrgInfo } from '@/utils/utils';

import styles from './index.less';

const { locale } = new Locale('component.companyDepart');

const generateTreeData = originTreeData => {
    const flattenTreeData = [];
    const getTreeData = (
        data = [],
        fieldsName = { value: 'organizationCode', title: 'organizationName' },
        parent = {}
    ) =>
        data.map(item => {
            const treeNode = {
                ...item,
                value: item[fieldsName.value],
                title: item[fieldsName.title],
                key: item[fieldsName.value],
                parent
            };
            treeNode.children = item.children ? getTreeData(item.children, fieldsName, treeNode) : item.children;
            flattenTreeData.push(treeNode);
            return treeNode;
        });
    const treeData = getTreeData(originTreeData);
    return { treeData, flattenTreeData };
};

// 获取最近的父节点中，organizationType为2或1的值，如果父节点中都没有2或1的值，使用当前用户的公司companyCode
// 1是集团，2是公司，3是部门
const getCodes = (treeNode, value, userCompanyCode, level = 0) => {
    if (!treeNode) {
        return {
            nextCompanyId: userCompanyCode,
            nextDepartmentId: value
        };
    }
    if (treeNode.organizationType === 2 || treeNode.organizationType === 1) {
        return {
            nextCompanyId: level ? treeNode.value : value,
            nextDepartmentId: level ? value : undefined
        };
    }
    return getCodes(treeNode.parent, value, userCompanyCode, level + 1);
};

const CompanyDepart = React.forwardRef(
    (
        {
            onChange,
            value,
            companyProps,
            wrapStyle,
            treeStyle,
            needPermission = true,
            extraQuery = {},
            allowClear = false,
            ...rest
        },
        ref
    ) => {
        const { firstCompanyCode, firstDepartmentCode, firstDepartmentPath, firstCompanyPath } = getUserOrgInfo();
        const [loading, setLoading] = React.useState(false);

        // 默认组件的value，有initialValue就优先使用，没有值用当前用户信息中的companyCode和departmentCode
        const { companyId, departmentId, organizationPath } = value ?? {
            companyId: firstCompanyCode,
            departmentId: firstDepartmentCode,
            organizationPath: firstDepartmentPath || firstCompanyPath
        };
        const [companyTree, setCompanyTree] = useState([]);
        const { treeData, flattenTreeData } = React.useMemo(() => generateTreeData(companyTree), [companyTree]);
        // 默认tree的value
        // 接口可能会只有部门或者只有公司，如果接口参数有只选部门或直选公司，那么默认值也必须相符
        const defaultValue = React.useMemo(() => {
            const types = extraQuery.organizationTypes ?? [];
            // 有可能可选项里没有当前默认值, 如果没有该选项直接返回空值
            const hasValue = val => flattenTreeData?.length && flattenTreeData.find(item => item.value === val);
            if (types.includes(3)) {
                return hasValue(departmentId) ? departmentId : null;
            }
            if (types.includes(2)) {
                return hasValue(companyId) ? companyId : null;
            }
            return hasValue(departmentId || companyId) ? departmentId || companyId : null;
        }, [departmentId, companyId, flattenTreeData]);

        const fetchCompanyTree = async () => {
            setLoading(true);
            const result = await request('/api/uc/org/v1/orgLinkList', {
                method: 'POST',
                data: {
                    organizationPermissions: Number(needPermission),
                    parentOrgPathListHasSelf: firstCompanyPath,
                    showTreeFlag: 1,
                    ...extraQuery
                }
            });
            setLoading(false);
            if (result && result.code === 10000) {
                const preprocessDataItem = array =>
                    array?.map(item => {
                        if (item?.children?.length) {
                            // eslint-disable-next-line no-param-reassign
                            item.children = preprocessDataItem(item.children);
                        }
                        return {
                            ...item,
                            organizationName: `${item.organizationName}${item.auditStatus === 1 ? ' (审批中)' : ''}`
                        };
                    });
                const permissionCompanyTree = preprocessDataItem(result.data);
                setCompanyTree(permissionCompanyTree || []);
            }
        };

        const handleCompanyChange = React.useCallback(
            newValue => {
                const node = flattenTreeData.find(item => item.value === newValue) || {};
                const { nextCompanyId, nextDepartmentId } = getCodes(node, newValue, firstCompanyCode);
                const { organizationPath: nodePath } = node;
                onChange({
                    companyId: nextCompanyId,
                    departmentId: nextDepartmentId,
                    organizationPath: nodePath
                    // node // 这个咨询后说是没用到，如果输出这个值会导致埋点数据转换出问题
                });
            },
            [treeData, flattenTreeData]
        );

        useEffect(() => {
            // 默认给个值
            if (!value) {
                // const node = flattenTreeData.find(item => item.value === defaultValue);
                onChange({
                    companyId,
                    departmentId,
                    organizationPath
                    // node
                });
            }
            fetchCompanyTree();
        }, []);

        return (
            <Spin spinning={loading} wrapperClassName={styles.companyDepartSpin}>
                <div ref={ref} style={{ ...wrapStyle }}>
                    <TreeSelect
                        showSearch
                        placeholder={locale('gs')}
                        style={{ width: 150, ...treeStyle }}
                        value={loading ? [] : defaultValue}
                        allowClear={allowClear}
                        dropdownStyle={{ maxHeight: 400, maxWidth: 240, overflow: 'auto' }}
                        treeDefaultExpandAll
                        treeNodeFilterProp="title"
                        treeData={treeData}
                        onChange={handleCompanyChange}
                        {...companyProps}
                        {...rest}
                    />
                </div>
            </Spin>
        );
    }
);

CompanyDepart.propTypes = {
    onChange: PropTypes.func,
    /**
     * company的Select属性
     */
    companyProps: PropTypes.object,
    /**
     * 是否需要权限控制
     */
    needPermission: PropTypes.bool
};

CompanyDepart.defaultProps = {
    onChange: () => {},
    companyProps: {},
    needPermission: true
};

export default CompanyDepart;
